<template>
  <div class="app-container project-container">
    <div class="app-container container template-tree">
      <div class="header">
        <div class="header-icon"></div>
        <div class="header-title">模块</div>
      </div>
      <div class="tree-box" v-loading="isTreeLoading" element-loading-text="加载中">
        <el-tree
          ref="tree"
          :data="templateTree"
          :default-expand-all="true"
          :expand-on-click-node="false"
          :highlight-current="level === 3"
          :node-key="nodeKey"
          :props="defaultProps"
          draggable
          :allow-drop="allowDrop"
          @node-drag-end="nodeDragEnd"
        >
          <template #default="{ node, data }">
            <div class="custom-tree-node" @click="handleNodeClick(node, data)">
              <div v-if="!data.isEdit" class="custom-tree-node__label">{{ data.standardName }}</div>
              <el-input v-else v-model="data.editLabel" />
            </div>
            <div class="tree-node-icon">
              <svg-icon iconClass="submit-icon" v-show="data.isEdit" @click="handelSubmitNode(data)" />
              <svg-icon iconClass="add-icon" v-show="node.level !== 3" @click="handelAddNode(node, data)" />
              <svg-icon iconClass="edit-icon" v-show="!data.isEdit" @click="handelEditNode(node, data)" />
              <svg-icon iconClass="del-icon" @click="handelDelNode(data)" />
              <svg-icon iconClass="vertical-drag" />
            </div>
          </template>
        </el-tree>
      </div>
      <el-button type="primary" :icon="Plus" @click="handelAddTemplate(-1)">新建模块</el-button>
    </div>
    <div class="container template-detail">
      <template v-if="level === 3">
        <div class="app-container header-box">
          <div class="header">
            <div class="header-icon"></div>
            <div class="header-title">工艺详情</div>
          </div>
          <el-button type="primary" plain size="large" v-show="isFormDisabled" @click="handelEditTemplate">编辑</el-button>
        </div>
        <div class="app-container template-detail-form" v-loading="isFormLoading" element-loading-text="加载中...">
          <el-form :model="form" label-width="auto">
            <el-form-item label="工艺标准说明">
              <el-input
                v-model="form.standardDesc"
                type="textarea"
                :disabled="isFormDisabled"
                placeholder="请输入标准描述"
                :maxlength="500"
                :autosize="{ minRows: 4 }"
                show-word-limit
              />
            </el-form-item>
            <el-form-item label="优劣势说明">
              <el-input
                v-model="form.shortcomingDesc"
                type="textarea"
                :disabled="isFormDisabled"
                placeholder="请输入标准描述"
                :maxlength="500"
                :autosize="{ minRows: 4 }"
                show-word-limit
              />
            </el-form-item>
            <el-form-item label="工艺标准图">
              <CustomUpdate
                :file-list="picData"
                :disabled="isFormDisabled"
                multiple
                tip="只能上传jpg/png，且不超过10M，最大支持上传9张"
                accept=".jpg,.png"
                :max-size="10"
                :max-length="9"
                @upload-success="uploadImage"
                @upload-remove="uploadImageRemove"
              />
            </el-form-item>
            <el-form-item label="工艺标准视频">
              <CustomUpdate
                :file-list="videoData"
                :disabled="isFormDisabled"
                multiple
                fileType="video"
                item-size="113px"
                accept=".avi,.mov,.mp4,.wmv"
                tip="只能上传 avi/mov/mp4/wmv 文件格式，单个不超过200MB，最大支持6个"
                :max-size="200"
                :max-length="6"
                @upload-success="uploadVideo"
                @upload-remove="uploadVideoRemove"
              />
            </el-form-item>
          </el-form>
        </div>
        <div class="option-btns">
          <!--          <el-button @click="handelCancel" size="large">取消</el-button>-->
          <el-button type="primary" size="large" :loading="isSubmitLoading" @click="handelSubmitClick" v-show="!isFormDisabled"
            >确定</el-button
          >
        </div>
      </template>
      <el-empty v-else />
    </div>
  </div>
</template>

<script setup>
import { getCurrentInstance, ref } from "vue";
import { Plus } from "@element-plus/icons-vue";
import { debounce } from "lodash";
import CustomUpdate from "./components/ImageVideoUpload";
import * as utils from "./utils";
import * as templateApis from "@/api/projectConfig/acceptanceCriteria";

const { proxy } = getCurrentInstance();

const nodeKey = "templateId";
const defaultProps = {
  children: "children",
  label: "standardName"
};
const templateTree = ref([]);
const isTreeLoading = ref(false);
const getStandardTemplateTree = async () => {
  try {
    isTreeLoading.value = true;
    const { data } = await templateApis.standardTemplateTree();
    templateTree.value = data || [];
    isTreeLoading.value = false;
  } catch (err) {
    isTreeLoading.value = false;
  }
};

const isFormLoading = ref(false);
const level = ref(1);
const handleNodeClick = (treeNode, data) => {
  if (data.isEdit) return;
  level.value = treeNode.level;
  if (treeNode.level !== 3) {
    form.value = { ...utils.initFormData };
    isFormDisabled.value = false;
    return;
  }
  const templateId = data?.templateId ?? "";
  isFormDisabled.value = true;
  getStandardTemplateDetail(templateId);
};
const handelAddTemplate = () => {
  isFormDisabled.value = false;
  level.value = 1;
  form.value = { ...utils.initFormData };
  templateTree.value.unshift({ isEdit: true, editLabel: "", format: "", parentId: 0 });
};
const handelEditTemplate = () => {
  isFormDisabled.value = false;
};
const handelAddNode = (node, data) => {
  utils.updateChildrenById(templateTree.value, data, nodeKey);
};
const handelEditNode = (node, data) => {
  data.isEdit = true;
  data.editLabel = data.standardName;
};
const handelSubmitNode = async data => {
  const addData = {
    templateId: data.templateId,
    parentId: data.parentId,
    standardName: data.editLabel,
    format: data.format || ""
  };
  const requestApi = addData.templateId ? templateApis.updateStandardTemplate : templateApis.addStandardTemplate;
  await requestApi(addData);
  getStandardTemplateTree();
};
const handelDelNode = data => {
  if (!data.templateId) {
    utils.deleteNode(templateTree.value, data.templateId, nodeKey);
    return;
  }
  proxy.$modal
    .confirm("确定删除该节点吗？", "提示")
    .then(async () => {
      await templateApis.deleteStandardTemplate(data.templateId);
      if (level.value === 3) {
        level.value = 2;
        form.value = { ...utils.initFormData };
      }
      getStandardTemplateTree();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
};
/**
 * TODO：详情数据不合理，应该由后端传回对象
 */
const handelDetailData = data => {
  const picIds = data?.picIds ? data.picIds?.split(",") : [];
  const picUrls = data?.picUrls ? data.picUrls?.split(",") : [];
  const videoIds = data?.videoIds ? data.videoIds?.split(",") : [];
  const videoUrls = data?.videoUrls ? data.videoUrls?.split(",") : [];
  picIds.forEach((item, index) => {
    picData.value.push({ fileId: item, fileUrl: picUrls[index], url: picUrls[index] });
  });
  videoIds.forEach((item, index) => {
    videoData.value.push({ fileId: item, fileUrl: videoUrls[index], url: videoUrls[index] });
  });
  // TODO: 是否填写，应该有后端返回状态
  if (!data.picIds && !data.picUrls && !data.videoIds && !data.videoUrls && !data.standardDesc && !data.shortcomingDesc) {
    isFormDisabled.value = false;
  }
};
const getStandardTemplateDetail = async templateId => {
  try {
    isFormLoading.value = true;
    picData.value = [];
    videoData.value = [];
    const { data } = await templateApis.standardTemplateDetail(templateId);
    handelDetailData(data);
    form.value = data;
    isFormLoading.value = false;
  } catch (err) {
    isFormLoading.value = false;
  }
};

let deptOrder = [];
let isBrotherNode = true;
const allowDrop = (draggingNode, dropNode, type) => {
  if (type === "inner") {
    return false;
  }
  const draggingLabel = draggingNode.data.standardName;
  const dropNodeLabel = dropNode.data.standardName;
  utils.getNodeInfo(templateTree.value, draggingLabel, (item, index, arr) => {
    deptOrder = arr;
  });
  isBrotherNode = deptOrder.some(node => node.standardName === dropNodeLabel);
  return isBrotherNode;
};
const nodeDragEnd = async () => {
  if (!isBrotherNode) {
    deptOrder = [];
    return proxy.$modal.msgError("只允许同级拖动");
  }
  let postData = deptOrder.map(item => item[nodeKey]);
  await templateApis.sortStandardTemplate(postData);
};

const isSubmitLoading = ref(false);
const isFormDisabled = ref(false);
const picData = ref([]);
const videoData = ref([]);
const form = ref({ ...utils.initFormData });

const uploadImage = data => {
  picData.value.push({
    ...data
  });
};
const uploadImageRemove = index => {
  picData.value.splice(index, 1);
};
const uploadVideo = data => {
  videoData.value.push({
    ...data
  });
};
const uploadVideoRemove = index => {
  videoData.value.splice(index, 1);
};

const handelSubmitData = () => {
  let picIds = [],
    picUrls = [],
    videoIds = [],
    videoUrls = [];
  picData.value.forEach(item => {
    picIds.push(item.fileId);
    picUrls.push(item.fileUrl);
  });
  videoData.value.forEach(item => {
    videoIds.push(item.fileId);
    videoUrls.push(item.fileUrl);
  });
  return { picIds: picIds.join(","), picUrls: picUrls.join(","), videoIds: videoIds.join(","), videoUrls: videoUrls.join(",") };
};
const submitFormData = async () => {
  try {
    isSubmitLoading.value = true;
    const submitData = {
      ...form.value,
      ...handelSubmitData()
    };
    const requestApi = form.value.templateId ? templateApis.updateStandardTemplate : templateApis.addStandardTemplate;
    await requestApi(submitData);
    proxy.$modal.msgSuccess("操作成功");
    isSubmitLoading.value = false;
  } catch (err) {
    isSubmitLoading.value = false;
  }
};
const handelSubmitClick = debounce(submitFormData, 500);
const handelCancel = () => {};

getStandardTemplateTree();
</script>

<style scoped lang="scss">
@import "acceptanceCriteria";
</style>
